package com.ynwt.jms;

import com.ynwt.domain.ReplyMsg;
import com.ynwt.enums.ReplyMsgType;
import com.ynwt.repository.ReplyMsgDao;
import com.ynwt.util.JsonUtil;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.transaction.Transactional;
import java.util.Random;

/**
 * Created by huangying on 2017/5/2.
 */
@Service
public class QueueServer {


    @JmsListener(destination = "test.queue")
    @Transactional
    public void receive(Message message) {
        System.out.println(message);
        System.out.println(JsonUtil.toJsonStr(message));
        try {
            if (message instanceof ActiveMQTextMessage && !message.getJMSRedelivered()) {
                ActiveMQTextMessage textMessage = (ActiveMQTextMessage) message;

    //            try {
    //                System.out.println(textMessage.getText());
    //            } catch (JMSException e) {
    //                e.printStackTrace();
    //            }
                try {
                    ReplyMsg replyMsg = new ReplyMsg();
                    replyMsg.setKeyWord("hi");
                    replyMsg.setText("hay, man!");
                    replyMsg.setMsgType(ReplyMsgType.TEXT);
                    replyMsgDao.save(replyMsg);
                    Random random = new Random();
                    int sleepTime = random.nextInt(1000) + 1;
                    System.out.println(sleepTime);
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    //            System.out.println(textMessage);
                jmsTemplate.convertAndSend(textMessage.getJMSReplyTo(), "收到。");
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private ReplyMsgDao replyMsgDao;
}
